package com.lagou.controller;

import com.lagou.entity.User;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private Redisson redisson;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {

        String uploadKey = "VIDEO_UPLOAD_NUM";
        RLock lock = redisson.getLock(uploadKey);
        // 加锁
        lock.lock(30, TimeUnit.SECONDS);

        System.out.println("加锁成功");

        try {
            Integer videoNum = Integer.valueOf(stringRedisTemplate.opsForValue().get("videoNum"));
            if (videoNum > 0) {
                videoNum--;
                stringRedisTemplate.opsForValue().set("videoNum", videoNum + "");
                System.out.println("剩余数量-1, 剩余" + videoNum);

                if (file.isEmpty()) {
                    throw new RuntimeException();
                }

                String substring = "D:\\download\\";

                String originalFilename = file.getOriginalFilename();

                String newFileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));

                String uploadPath = substring + "upload\\";
                System.out.println("uploadPath = " + uploadPath);

                File filePath = new File(uploadPath, newFileName);

                if (!filePath.getParentFile().exists()) {
                    filePath.getParentFile().mkdirs();
                    System.out.println("创建目录成功");
                }

                file.transferTo(filePath);
            } else {
                System.out.println("数量不足!");
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        return "OK";
    }
}
